﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using HtmlAgilityPack;
using Soufun.DB;
using Soufun.Model;
using Soufun.DAL;

namespace Soufun
{
    public partial class AddProjectInfo : DevExpress.XtraEditors.XtraForm
    {
        public AddProjectInfo()
        {
            InitializeComponent();
        }

        private DProjectUrl _dProjectUrl = new DProjectUrl();
        private DProjectArea _dProjectArea = new DProjectArea();

        private string _strTablePath =
"//html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[2]/table[1]" +
"/tbody[1]/tr[2]/td[1]/table[2]/tbody[1]/tr[1]/td[1]/table[1]" +
"/tbody[1]/tr[2]/td[1]/table[1]/tr[2]/td[1]//table[3]/tr[1]" +
"/td[1]/table[1]/tbody[1]/tr";
        private string _strTdPath = "//td";

        private void AddProjectInfo_Load(object sender, EventArgs e)
        {
            //String[] files = Directory.GetFiles(Application.StartupPath + "\\dataExcel");
            //string fileName = System.IO.Path.GetFileName(files[0]);
        }



        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (!CheckedInput())
            {
                return;
            }
            textEdit_projectName.Enabled = false;
            textEdit_projectUrl.Enabled = false;
            btnEdit_excelPath.Enabled = false;
            btn_excelPath2.Enabled = false;
            btn_add.Enabled = false;
            btn_cancel.Enabled = false;
            Thread thread = new Thread(AddDataInThreat){IsBackground = true};
            thread.Start();              
        }

        private void AddDataInThreat()
        {
            string urlExist = _dProjectUrl.ExistUrl(textEdit_projectUrl.Text);
            if (urlExist != "")
            {
                XtraMessageBox.Show("该Url已存在，使用项目为【" +
                    urlExist + "】，请核对！");
                BeginInvoke(new MethodInvoker(() =>
                {
                    marqueeProgressBarControl1.Visible = false;
                    textEdit_projectName.Enabled = true;
                    textEdit_projectUrl.Enabled = true;
                    btnEdit_excelPath.Enabled = true;
                    btn_excelPath2.Enabled = true;
                    btn_cancel.Enabled = true;
                    btn_add.Enabled = true;
                }));
                return;
            }

            ProjectUrlInfo model = new ProjectUrlInfo();
            model.ProjectName = textEdit_projectName.Text.Trim();
            model.ProjectUrl = textEdit_projectUrl.Text.Trim();
            int projectId = _dProjectUrl.Add(model);

            DataTable dt = (DataTable)gridControl1.DataSource;
            DataTable dt2 = (DataTable)gridControl2.DataSource;

            BeginInvoke(new MethodInvoker(() =>
                {
                    Console.WriteLine("正在获取网上数据格式");
                    marqueeProgressBarControl1.Text = "正在获取网上数据格式";
                    marqueeProgressBarControl1.Visible = true;
                }));


            string httpText = Common.GetHtmlTextByUrl(model.ProjectUrl);

            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(httpText);
            HtmlNode rootNode = document.DocumentNode;
            HtmlNodeCollection categoryNodeList = rootNode.SelectNodes(_strTablePath);

            HtmlNode trNode = HtmlNode.CreateNode(categoryNodeList[3].OuterHtml);
            HtmlNodeCollection tdNodes = trNode.SelectNodes(_strTdPath);

            //----------------------判断当前读取的数据库行数和列数是不是与提供网址的行数列数一样
            //----------------------dt多了一个
            if (!(dt.Rows.Count == categoryNodeList.Count - 3 && dt.Columns.Count == tdNodes.Count))
            {
                _dProjectUrl.DeleteById(projectId);
                XtraMessageBox.Show("本地数据与网页上的数据格式不一样，请检查对应的格式。");
                BeginInvoke(new MethodInvoker(() =>
                {
                    Console.WriteLine("本地数据与网页上的数据格式不一样，请检查对应的格式。");
                    marqueeProgressBarControl1.Text = "本地数据与网页上的数据格式不一样，请检查对应的格式";
                    marqueeProgressBarControl1.Visible = true;
                    marqueeProgressBarControl1.Properties.Stopped = true;
                    textEdit_projectName.Enabled = true;
                    textEdit_projectUrl.Enabled = true;
                    btnEdit_excelPath.Enabled = true;
                    btn_excelPath2.Enabled = true;
                    btn_cancel.Enabled = true;
                    btn_add.Enabled = true;
                }))
             ;
                return;
            }

            if (projectId < 0)
            {
                XtraMessageBox.Show("添加数据失败，请检测数据库连接是否正常!");
                return;
            }
            bool flag1 = false;
            bool flag2 = false;

            string strResult = "";
            if (btnEdit_excelPath.Text != "")
            {
                int insertRowsCount = 500;//一次性插入数据库行数
                int succeedrows = 0;//成功插入数据行数
                StringBuilder strSql = new StringBuilder();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    if (i % insertRowsCount == 0)
                    {
                        strSql = new StringBuilder();
                        strSql.Append("Insert into tProjectAreaInfo (");
                        strSql.Append("ProjectId,BuildingID,UnitID,");
                        strSql.Append("FloorID,ProjectAreaString)");
                        strSql.Append(" value  ");
                    }
                    strSql.Append("(");
                    int buildingId = 0;
                    int unitId = 0;
                    int.TryParse(row[0].ToString(), out buildingId);
                    int.TryParse(row[1].ToString(), out unitId);

                    strSql.Append(projectId);
                    strSql.Append(",'");
                    strSql.Append(buildingId);
                    strSql.Append("','");
                    strSql.Append(unitId);
                    strSql.Append("','");
                    strSql.Append(row[2]);
                    strSql.Append("','");
                    for (int j = 3; j < dt.Columns.Count; j++)
                    {
                        float temp = 0;
                        float.TryParse(row[j].ToString(), out temp);
                        strSql.Append(temp);
                        if (j != dt.Columns.Count - 1)
                        {
                            strSql.Append(",");
                        }
                    }
                    strSql.Append("'),");

                    if ((i + 1) % insertRowsCount == 0
                        || i == dt.Rows.Count - 1)
                    {
                        strSql.Remove(strSql.Length - 1, 1);
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                }
                if (dt.Rows.Count == succeedrows)
                {
                    flag1 = true;
                    strResult = "第一张Excel数据保存成功！";
                }
                else
                {
                    int failedCount = dt.Rows.Count - succeedrows;
                    strResult = "第一张Excel数据保存异常：" +
                      "共记" + dt.Rows.Count + "条数据，其中"
                     + failedCount + "条数据添加失败！";
                }
            }
           
            if (btn_excelPath2.Text != "")
            {
                int insertRowsCount = 500;//一次性插入数据库行数
                int succeedrows = 0;//成功插入数据行数
                StringBuilder strSql = new StringBuilder();
                DataTable dtHouseType = dt2.Copy();
                dtHouseType.Rows.Clear();
                foreach (DataRow dataRow in dt2.Rows)
                {
                    if (dataRow[0].ToString() != "" 
                        && dataRow[1].ToString() != "")
                    {
                        dtHouseType.Rows.Add(dataRow.ItemArray);
                    }
                }


                for (int i = 0; i < dtHouseType.Rows.Count; i++)
                {
                    DataRow row = dtHouseType.Rows[i];
                    if (i % insertRowsCount == 0)
                    {
                        strSql = new StringBuilder();
                        strSql.Append("Insert into tProjectHouseTypeInfo (");
                        strSql.Append("ProjectId,UnitID,HouseID,");
                        strSql.Append("HouseArea,HouseType,HouseCount)");
                        strSql.Append(" value  ");
                    }
                    strSql.Append("(");
                    int unitId = 0;
                    string houseId = "";
                    float houseArea = 0;
                    int houseCount = 0;
                    int.TryParse(row[0].ToString(), out unitId);
                    houseId = row[1].ToString();
                    float.TryParse(row[2].ToString(), out houseArea);
                    int.TryParse(row[4].ToString(), out houseCount);

                    strSql.Append(projectId);
                    strSql.Append(",'");
                    strSql.Append(unitId);
                    strSql.Append("','");
                    strSql.Append(houseId);
                    strSql.Append("',");                 
                    strSql.Append(houseArea);
                    strSql.Append(",'");
                    strSql.Append(row[3]);
                    strSql.Append("',");
                    strSql.Append(houseCount);
                    strSql.Append("),");

                    if ((i + 1) % insertRowsCount == 0
                        || i == dtHouseType.Rows.Count - 1)
                    {
                        strSql.Remove(strSql.Length - 1, 1);
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                }
                if (dtHouseType.Rows.Count == succeedrows)
                {
                    flag2 = true;
                    strResult += "第二张Excel数据保存成功！";

                }
                else
                {
                    int failedCount = dtHouseType.Rows.Count 
                        - succeedrows;
                    strResult += "第二张Excel数据保存异常：" +
                        "共记" + dtHouseType.Rows.Count + "条数据，其中"
                     + failedCount + "条数据添加失败！";
                }
              
            }
            if (flag1 && flag2)
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    textEdit_projectName.Text = "";
                    textEdit_projectUrl.Text = "";
                    btnEdit_excelPath.Text = "";
                    btn_excelPath2.Text = "";
                    gridControl1.DataSource = null;
                    gridControl2.DataSource = null;
                    btn_add.Enabled = true;
                }));
            }

            BeginInvoke(new MethodInvoker(() =>
            {
                marqueeProgressBarControl1.Visible = false;
                textEdit_projectName.Enabled = true;
                textEdit_projectUrl.Enabled = true;
                btnEdit_excelPath.Enabled = true;
                btn_excelPath2.Enabled = true;
                btn_cancel.Enabled = true;
            }));
            XtraMessageBox.Show(strResult);
        }

        private void btnEdit_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;           
            btnEdit_excelPath.Text = fileName;
           
            gridControl1.DataSource = null;
            gridView1.Columns.Clear();
            gridView1.GroupPanelText = "请选择Excel文件";
            if (fileName=="")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds==null || ds.Tables.Count ==0
                || ds.Tables[0].Columns.Count<4)
            {
                //选择的Excel名称必须为默认的Sheet1,且最少应有四列数据
                XtraMessageBox.Show("选择的Excel文件数据格式有问题,请核对！");
                btnEdit_excelPath.Text = "";
                return;
            }
            gridControl1.DataSource = ds.Tables[0];
            gridView1.GroupPanelText = "共有" + ds.Tables[0].Rows.Count+"条数据";
        }

        public bool CheckedInput()
        {
            string projectName = textEdit_projectName.Text;
            string projectUrl = textEdit_projectUrl.Text;
            if (projectName.Trim()=="")
            {
                XtraMessageBox.Show("项目名称不能为空！");
                textEdit_projectName.Focus();
                return false;
            }
            if (Encoding.GetEncoding("gbk").GetBytes(projectName).Length>100)
            {
                XtraMessageBox.Show("项目名称长度过长，不能超过100个字节！");
                textEdit_projectName.Focus();
                return false;
            }
            if (projectUrl.Trim() == "")
            {
                XtraMessageBox.Show("项目Url不能为空！");
                textEdit_projectUrl.Focus();
                return false;
            }
            if (Encoding.GetEncoding("gbk").GetBytes(projectUrl).Length >200)
            {
                XtraMessageBox.Show("项目Url长度过长，不能超过200个字节！");
                textEdit_projectUrl.Focus();
                return false;
            }
            if (btnEdit_excelPath.Text == "")
            {
                XtraMessageBox.Show("请选择项目对应的面积信息Excel文件！");
                btnEdit_excelPath.Focus();
                return false;
            }
            if (btn_excelPath2.Text == "")
            {
                XtraMessageBox.Show("请选择项目户型信息Excel文件！");
                btn_excelPath2.Focus();
                return false;
            }
            return true;
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            if (textEdit_projectName.Text.Trim() == "" &&
                 textEdit_projectUrl.Text == "" &&
                 btnEdit_excelPath.Text == "")
            {
                Close();
            }
            else
            {
                textEdit_projectName.Text = "";
                textEdit_projectUrl.Text = "";
                btnEdit_excelPath.Text = "";    
            }            
        }

        private void btn_excelPath2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath2.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0
                || ds.Tables[0].Columns.Count < 4)
            {                
                XtraMessageBox.Show("选择的Excel文件数据格式有问题,请核对！");
                btn_excelPath2.Text = "";
                return;
            }
            gridControl2.DataSource = ds.Tables[0];
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            AddHouseTypeForm form = new AddHouseTypeForm();
            form.ShowDialog();
        }


        #region 窗体效果
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.btn_exit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.btn_exitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.Close();
            }
        }

        #endregion
    }
}